package com.kevin.data.batch.component;

import com.kevin.data.batch.configuration.BizJobListener;
import jakarta.annotation.Resource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 异步处理
 */
@Component
public class AsyncBatchComponent {

    @Resource
    private JobRepository jobRepository;

    @Resource
    private BizJobListener jobListener;

    @Resource
    private PlatformTransactionManager transactionManager;

    @Bean("asyncJob")
    public Job asyncJob() {
        return new JobBuilder("asyncJob", jobRepository).start(asyncFlow1())
                .split(new SimpleAsyncTaskExecutor()).add(asyncFlow2()).end().listener(jobListener).build();
    }

    private Flow asyncFlow1() {
        return new FlowBuilder<Flow>("asyncFlow1").start(asyncStep1()).next(asyncStep2()).build();
    }

    private Flow asyncFlow2() {
        return new FlowBuilder<Flow>("asyncFlow2").start(asyncStep3()).build();
    }

    private Step asyncStep1() {
        return new StepBuilder("asyncStep1", jobRepository).tasklet((contribution, chunkContext) -> {
            System.err.println("asyncStep1 test......");
            return RepeatStatus.FINISHED;
        }, transactionManager).allowStartIfComplete(true).build();
    }

    private Step asyncStep2() {
        return new StepBuilder("asyncStep2", jobRepository).tasklet((contribution, chunkContext) -> {
            System.err.println("asyncStep2 test......");
            return RepeatStatus.FINISHED;
        }, transactionManager).allowStartIfComplete(true).build();
    }

    private Step asyncStep3() {
        return new StepBuilder("asyncStep3", jobRepository).tasklet((contribution, chunkContext) -> {
            System.err.println("asyncStep3 test......");
            return RepeatStatus.FINISHED;
        }, transactionManager).allowStartIfComplete(true).build();
    }

}
